package com.study.quiz.utils;

import com.study.quiz.mapper.UserMapper;
import com.study.quiz.pojo.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author CJunGod
 * @create 2020-03-05 14:05
 **/
@Component
public class VerifyCookieUtil {

    @Value("${token}")
    private String userToken;

    @Resource
    private UserMapper userMapper;

    public User VerifyUser(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie c : cookies) {
                if (c.getName().equals(userToken)) {
                    User byToken = userMapper.findByToken(c.getValue());
                    if (byToken != null) {
                        request.getSession().setAttribute("user", byToken);
                        request.getSession().setMaxInactiveInterval(600);
                    }
                    return byToken;
                }
            }
        }

        return null;

    }
}
